22. Solution: Use the Cursor

Use the Cursor Solution

In this exercise you wrapped everything up by using the data from the Cursor to finish QuizExample.

Notes on Solution Code

Below is the final code for nextWord, which does the most cursor manipulations.

First, it checks if the cursor has been set. If it has, it tries to move the cursor to the next value, using moveToNext. This will return false if it cannot, in which case, we call moveToFirst to go back to the first row in the Cursor.

    public void nextWord() {
        if (mData != null) {
            // Move to the next position in the cursor, if there isn't one, move to the first
            if (!mData.moveToNext()) {
                mData.moveToFirst();
            }

At this point, the cursor is positioned at the correct row, so we set the definition view to invisible, change the button text to "Show Definition"

            // Hide the definition TextView
            mDefinitionTextView.setVisibility(View.INVISIBLE);

            // Change button text
            mButton.setText(getString(R.string.show_definition));

Finally we setup the correct values for the word and the hidden definition text, using the Cursors' getString method.

            // Get the next word
            mWordTextView.setText(mData.getString(mWordCol));
            mDefinitionTextView.setText(mData.getString(mDefCol));

            mCurrentState = STATE_HIDDEN;
        }
    }

Note that mWordCol and mDefCol were set in the AsyncTask's onPostExecute method:

        @Override
        protected void onPostExecute(Cursor cursor) {
            super.onPostExecute(cursor);
            mData = cursor;
            // Get the column index, in the Cursor, of each piece of data
            mDefCol = mData.getColumnIndex(DroidTermsExampleContract.COLUMN_DEFINITION);
            mWordCol = mData.getColumnIndex(DroidTermsExampleContract.COLUMN_WORD);
            // Set the initial state
            nextWord();
        }

The solution diff can be found below.

Solution Code

Solution: [T08.03-Solution-FinishQuizExample][Diff]